package swimv2.session;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.RemoteBinding;


import swimv2.entity.*;

/**
 * Session Bean implementation class StatisticModuleBean
 */
@Stateless
@RemoteBinding( jndiBinding = "IStatisticModuleRemote" )
public class StatisticModuleBean implements IStatisticModuleRemote {
	@PersistenceContext(unitName = "swimv2")
	protected EntityManager manager;

    /**
     * Default constructor. 
     */
    public StatisticModuleBean() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public Statistics getStatistics(Integer user_id) {
		Query q= manager.createQuery("SELECT sum(f.punteggio) FROM Feedback f JOIN Message m on f.request=m.id WHERE m.receiver = :nome");
		q.setParameter( "nome", user_id );	
		
		Statistics s = new Statistics();
		s.setPunteggio((Integer) q.getSingleResult());
		
		return s;
	}

	@Override
	public List<Statistics> getTopUsers(Integer start, Integer stop) {
		
		Query q= manager.createQuery("select new swimv2.session.Statistics(sum(f.punteggio), m.receiver) FROM Feedback f, Message m WHERE f.request.id= m.id GROUP BY m.receiver");
		List<Statistics> completa = (List<Statistics>)q.getResultList();
		
		List<Statistics> top = new ArrayList<Statistics>();
		
		for(int i=start; i<stop; i++){
			top.add(completa.get(i));
		}
		return top;
	}

}
